﻿<html>
	<head>
		<title>Stauffware.Essentials C# class library &ndash; Overview</title>
		<link href="../../documentation/Stauffware.css" rel="StyleSheet" type="text/css" media="screen, print" />
		<meta name="Stauffware" content="overview" />
		<style type="text/css" media="all">
			span.why { font-style:italic; padding-right:0.5em; }
		</style>
	</head>
	<body>
		<div style="float:right; text-align:right;">
			<p><a class="btn" href="../_READ_ME_.html">UP</a></p>
			<p class="update">last updated<br />30 July 2011</p>
		</div>
		<h1>Stauffware.Essentials C# class library<br />Overview</h1>
		<hr />

		<p>This is a detailed overview of the class library, providing a laundry list
			of the main components, their salient features, and why you should care.
			It doesn't pretend to be a complete programming reference; for that, refer 
			to the documentation generated from the XML comments in the source code. </p>

The Core Library
	Core
		Assertions
		Character Encodings
		Error Utilities
		ErrorOr
		Number Parsing - the Parser/Parse pattern
		Collections
		Miscellany
	Console
		ConsoleApp
		CmdLineParser
	IO
	Time



		<h3>A Brief History You Can Ignore</h3>
		<p>
			This class library grew organically over time, starting soon after C# became
			my language of preference in 2002.  Like many other personal toolboxes, it
			began as a handful of classes that I copied as needed from one project to another,
			and later grew into an independent DLL that accompanied me through Way Too Many
			Job Changes in the tumultuous decade that followed.  It lived under the namespace
			<code>StauffConsulting.Essentials</code>, until in 2011 I decided to formalize
			its status as open-source software, and moved it to its new home in the
			namespace <code>Stauffware.Common</code>.  This afforded me an opportunity
			to make a number of non-backward-compatible changes, under the cover of
			changing its major version number from 1 to 2.
		</p>

		<h3>Why?</h3>
		<p>Why did I create and continue to maintain this class library?
			Because I tend to gravitate more towards perfectionism than expedience.
			Because I hate writing ugly code, and hate even more having to maintain it.
			Because, as much as I love C# and .Net overall, Microsoft left out some
			important things, and got a few things Wrong.  You'll see that question 
			"Why?" repeated below, wherafter I provide justifications for why I've
			chosen to re-invent certain wheels.<a class="footnote" href="#Footnotes">1</a>
		</p>


		<h2>The Class Library</h2>
		<div class="sect">

			<h3>Core</h3>
			<div class="sect">
			
				<h4>Assertions</h4>
				<div class="sect">
					
					<p>If you don't know what an assertion is, then go read 
						<a href="http://en.wikipedia.org/wiki/Assertion_(computing)">the Wikipedia article</a>, 
						and if you've been programming for more than a year or so, 
						you really need to start talking shop with other 
						programmers.<a class="footnote" href="#Footnotes">2</a>
						A full discussion of assertions is beyond the scope of this context,
						but assertions are too important to not reiterate a few fundamentals:
						</p>
						<ul>
							<li>Assertions are a way of programmatically verifying things
								that you, the programmer, believe to be true (or had better
								be true).</li>
							<li>A failed assertion always indicates a <i>programming error</i> (a bug),
								never a user error.</li>
							<li>Never disable or remove an assertion in the release version of
								your software unless you can prove, objectively and conclusively,
								that either (a) the condition being checked for can never
								happen,<a class="footnote" href="#Footnotes">3</a> or 
								(b) the specific assertion in question has an unacceptable impact 
								on performance.<a class="footnote" href="#Footnotes">4</a></li>
						</ul>

					<pre class="example" style="float:right;"
>static int Average (ICollection&lt;int&gt; list, 
                    out int min, out int max)
{
    <span class="hilit">Require.NotNull(list, 
                   "list must not be null");
    Require.Condition(list.Count > 0, 
                     "list must not be empty");</span>
    min = int.MaxValue; max = int.MinValue; 
    long total = 0;
    foreach (int n in list)
    {
        min = Math.Min(min, n);
        max = Math.Max(max, n);
        total += n;
    }
    int avg = (int)(total / list.Count);
    <span class="hilit">Ensure.Condition(min &lt;= max);
    Ensure.Condition(avg &gt;= min && avg &lt;= max);</span>
    return avg;
}</pre>

					<div>
					<p>This class library consists primarily of a set of four static 
						classes which you should interpret as transitive imperative verbs, 
						with their methods serving as direct objects (in the linguistic 
						sense).<a class="footnote" href="#Footnotes">5</a>
						Those four classes each contain the same small set of methods, 
						including <code>NotNull(object)</code>, 
						<code>HasValue&lt;T&gt;(Nullable&lt;T&gt;)</code>,
						and <code>Condition(bool)</code>.
						There are also four corresponding Exception classes, instances of
						which are thrown to signal failed assertions.
						</p>


					<dl>
						<dt><code><b>Require</b></code></dt>
						<dd>This class is for specifying input requirements, also known as 
							<i>preconditions</i>, which are nearly always used in the first
							few lines of a method body.  They implement rules that the
							caller must abide by; therefore, a failed <code>Require</code> 
							is the fault of the caller, not the method in which the 
							<code>Require</code> appears.</dd>

						<dt><code><b>Ensure</b></code></dt>
						<dd>This class is for specifying output requirements, also known as
							<i>postconditions</i>, which are nearly always used immediately
							before a method returns.  They implement rules that the method
							agrees to abide by; therefore, a failed <code>Ensure</code> 
							is the fault of the method in which it appears.</dd>

						<dt><code><b>Assert</b></code></dt>
						<dd>This class is for expressing things you believe are true about
							the run-time state of your code.</dd>

						<dt><code><b>Assume</b></code></dt>
						<dd>A recent addition to this library, this class is for expressing 
							conditions that you <i>believe</i> are true about external things beyond
							your control, such as poorly documented 3rd-party interfaces.</dd>
					</dl>			
					</div>

					&nbsp;
		
					<p><span class="why">Why?</span> The .Net Framework provides two assertion methods (each with
						3 or 4 overloads): <code>System.Diagnostics.Debug.Assert</code> and
						<code>System.Diagnostics.Trace.Assert</code>.  These lack the added
						semantic value provided by <code>Require</code> and <code>Ensure</code>.
						The .Net Framework also lacks a failed-assertion exception. </p>

				</div>

				<h4>Character Encodings</h4>
				<div class="sect">
					<dl>
						<dt><code><b>CharEncoding</b></code></dt>
						<dd>The static methods of this class provide convenient conversions between
							Unicode, XML entities, and ASCII.
							<p><span class="why">Why?</span> <code>System.Web.HttpUtility.HtmlEncode</code> and
							<code>System.Net.WebUtility.HtmlEncode</code> don't properly handle some 
							characters, such as single-quote.</p></dd>

						<dt><code><b>Chars</b></code></dt>
						<dd>This static class contains read-only <code>CharEncoding</code> fields for
							over 250 of the most useful non-ASCII characters, such as copyright, degree sign,
							non-breaking space, math operators, and accented letters.  
							Each <code>CharEncoding</code> object
							has read-only properties to obtain the character's Unicode encoding, HTML
							named entity (if any), HTML decimal entity, HTML hex entity, and an ASCII
							approximation. For example, <code>Chars.LeftDoubleQuote</code> has property
							values <code>NamedEntity="&amp;ldquo;", DecimalEntity="&amp;#8220;", 
							HexEntity="&amp;#x201C;", Unicode="\u201C", AsciiApproximation="\""</code>.
							<p><span class="why">Why?</span> Because the .Net Framework doesn't have this.</p></dd>
					</dl>
				</div>

				<h4>Error Utilities</h4>
				<div class="sect">
					<p>This static class contains a small number of extremely useful methods to help
						with reporting errors:</p>
					<dl>
						<dt><code><b>DumpExceptionChain (Exception)</b></code></dt>
						<dd>Like <code>System.Exception.ToString()</code>, <code>DumpExceptionChain</code>
							creates a string containing an exception's message and stack trace.
							It also includes in the string the inner exception, recursively (something
							the original <code>Exception.ToString()</code> didn't do), <i>plus</i> the
							contents of <code>Exception.Data</code>.  But wait, there's more &ndash;
							now how much would you pay?  <code>DumpExceptionChain</code> also includes
							the values of all the properties of the exception object, regardless of
							its type. This means you get, for example, the values of 
							<code>System.IO.FileLoadException</code>'s <code>FileName</code> and 
							<code>FusionLog</code> properties.</dd>

						<dt><code><b>ValueToString (object)</b></code></dt>
						<dd>Returns a string representation of the given object in a format useful to
							C# programmers.</dd>
					</dl>
				</div>

				<h4>ErrorOr</h4>


				<h4 id="ParserParsePattern">Number Parsing &ndash; the Parser/Parse pattern</h4>
				<div class="sect">
					<p>The Stauffware class libraries introduce the "parser/parse" pattern, wherein
						a <i>parser</i> object parses a string and returns a 
						<i>parse</i><a class="footnote" href="#Footnotes">6</a> object,
						which may contain either the parsed value, an error message, or neither
						(if the input string was empty).</p>
					<dl>
						<dt><code><b>IParse&lt;T&gt;</b></code></dt>
						<dd>This read-only interface is the foundation for values returned by parsers.
							It has boolean properties <code>GotValue, IsError, IsEmpty</code>,
							of which exactly one will have a value of <code>true</code>, 
							and the other two <code>false</code>.  It has a <code>Value</code>
							property containing the the successfully parsed value, 
							an <code>ErrorMessage</code> property containing an error message 
							for failed parse attempts, a <code>ParsedText</code> property containing 
							the text that was parsed, and a <code>ToException</code> method that
							converts the <code>IParse</code> object into an exception object
							that can be thrown.<br />
							By convention, implementations of <code>IParse&lt;T&gt;</code> also provide
							implicit conversions from <code>IParse&lt;T&gt;</code> to <code>T</code>
							and to <code>IParseException</code>.</dd>

						<dt><code><b>ParseOptions</b></code></dt>
						<dd>This is a flags enum that specifies parsing options such as whether to
							ignore leading/trailing whitespace, and whether to parse the entire
							input string.  For each pair of parser/parse classes, there is a corresponding
							options enum which sort of inherits from <code>ParseOptions</code>.</dd>

						<dt><code><b><i>NumberParser&lt;T&gt;</i></b></code></dt>
						<dd>The class library provides <i>Parser</i> and <i>Parse</i> classes 
							for signed and unsigned integers of 8, 16, 32, and 64 bits, 
							for single and double floats, and for decimal values.  
							Each <code><i>Type</i>Parser</code> class includes a 
							<code>Parse(string)</code> method that returns a matching 
							<code><i>Type</i>Parse</code> object, and a set of constructors
							that take your choice of <code>IFormatProvider</code>, a 
							<code><i>Type</i>ParseOptions</code> enum, both, or neither.
							</dd>
					</dl>
					<p><span class="why">Why?</span> The .Net Framework provides two kinds of parse methods: 
						the first one ("Parse") returns the value of a successful parse, 
						or throws an exception on any sort of error.  The second one (TryParse) 
						provides the successfully parsed value via an output parameter,
						and returns a boolean indicating whether the parse was successful 
						&ndash; but gives you no indication as to <i>why</i> the parse failed.  
						In situations where parsing errors are common (such as validating user input), 
						you're stuck with choosing between a clumsy approach (wrapping the Parse 
						method in a try/catch block) and a rude approach (using TryParse, with 
						no way to provide an error message more meaningful than "nyah, nyah").</p>
				</div>

				<h4>Collections</h4>
				<div class="sect">
					<dl>
						<dt><code><b>IReadOnlyList&lt;T&gt;</b></code></dt>
						<dd>This interface contains all the members of 
							<code>System.Collections.Generic.IList&lt;T&gt;</code>,
							except for the ones that modify the list.
							<p><span class="why">Why?</span> The .Net Framework does provide a generic 
							<code>ReadOnlyCollection&lt;T&gt;</code> class, but they missed the boat 
							by not providing a corresponding <code>IReadOnlyCollection&lt;T&gt;</code>
							interface. <code>ReadOnlyCollection&lt;T&gt;</code> implements 
							<code>IList&lt;T&gt;</code>, which means that a violation of the 
							read-only restriction can only be detected at runtime.  By omitting 
							the offending methods altogether, <code>IReadOnlyList&lt;T&gt;</code> 
							enforces the read-only restriction at compile time.</p></dd>

						<dt><code><b>ReadOnlyList&lt;T&gt;</b></code></dt>
						<dd>A wrapper class for <code>System.Collections.Generic.List&lt;T&gt;</code>
							that implements the <code>IReadOnlyList&lt;T&gt;</code> interface.</dd>

						<dt><code><b>IReadOnlyDictionary&lt;Tkey, Tvalue&gt;</b></code></dt>
						<dd>This interface is equivalent to 
							<code>System.Collections.Generic.IDictionary&lt;T&gt;</code>,
							but without the members that modify the list.</dd>

						<dt><code><b>ReadOnlyDictionary&lt;T&gt;</b></code></dt>
						<dd>A wrapper class for <code>System.Collections.Generic.Dictionary&lt;T&gt;</code>
							that implements the <code>IReadOnlyDictionary&lt;T&gt;</code> interface.</dd>

					</dl>
				</div>

				<h4>Miscellany</h4>
				<div class="sect">
					<dl>
						<dt><code><b>ListString</b></code></dt>
						<dd>This class provides a convenient way to create a string containing
							a list of items separated by a delimiter (e.g. a comma).
							The constructor takes a prefix string to appear before the item list,
							a delimiter to place between items, a suffix string to appear after
							the item list, and a string to use if there are no items at all.
							<p><span class="why">Why?</span> Because I got tired of dealing with boundary conditions
							every time I wanted to stringize a list of things</p></dd>

						<dt><code><b>System.String Extension Methods</b></code></dt>
						<dd><code>bool&nbsp;Contains(char&nbsp;c); &nbsp; 
								int&nbsp;IndexOfEnd(string&nbsp;toSearchFor); &nbsp; 
								string&nbsp;TrimEnd(int&nbsp;numberOfCharsToRemove); &nbsp; 
								string&nbsp;Extract(int&nbsp;startPos,&nbsp;int&nbsp;length,&nbsp;out&nbsp;string&nbsp;extractedSubString);</code>
								</dd>

						<dt><code><b>NumUtils</b></code></dt>
						<dd>Contains static methods for converting numbers to strings using arbitrary bases
							and digit sets.</dd>

						<dt><code><b>Time_Extensions</b></code></dt>
						<dd>Extension functions for <code>System.DateTime</code>: 
							<code>Multiply(TimeSpan, int_or_double), Divide(TimeSpan, int_or_double), IsNegative(TimeSpan)</code>
							</dd>
						<dt></dt>
					</dl>
				</div>
	
			</div>

			<h3>Console</h3>
			<div class="sect">
				<dl>
					<dt><code><b>ConsoleUtils</b></code></dt>
					<dd>If you've ever written a console application and wanted to get rid 
						of the console window that pops up if there isn't one already, or 
						if you've ever written a windows application and wished it had a
						console window, then you'll appreciate this handful of static methods.  
						<code></code> </dd>

					<dt><code><b>AppExitCode</b></code></dt>
					<dd>This tiny class represents an exit code that can be returned by
						an application when it exits, typically used by console apps.
						Each instance of <code>AppExitCode</code> combines an integer 
						exit code and a description of what it means.  The class keeps
						a list of all the instances created, for displaying to the user.</dd>

					<dt><code><b>ConsoleApp</b></code></dt>
					<dd>Provides a framework for a console application, including error reporting,
						exception handling, and processing of command-line parameters.</dd>

					<dt><code><a href="CmdLineParser.html"><b>Command-Line Parsing</b></a></code></dt>
					<dd>Allows you to define command-line parameters by decorating variables
						with custom attributes.  Command-line parsing, integrated with <code>ConsoleApp</code>.</dd>
				</dl>			
			</div>


			<h3>IO</h3>
			<div class="sect">
				<dl>
					<dt><code><b>FileSystemPath</b></code></dt>
						<dd>What <code>System.IO.Path</code> should have been: a non-static class
							whose instances represent file system paths, either absolute or partial.
							Features include checking for wildcards, splitting a path into its
							component parts, path normalization, and converting between absolute
							and partial paths.
							</dd>

					<dt><code><b>RepeatingTextWriter</b></code></dt>
						<dd>This subclass of <code>System.IO.TextWriter</code> contains a list of
							<code>TextWriter</code> objects (provided by you) to which it copies 
							all its output.  In other words, <code>RepeatingTextWriter</code>
							gives you a transparent means of directing <code>TextWriter</code>
							output to multiple destinations at once.
							<p><span class="why">Why?</span> The .Net Framework doesn't provide anything like it.</p></dd>
				</dl>
			
			</div>

			<h3>Time</h3>
			<div class="sect">
			
				<dl>
					<dt><code><b>DateTimeParser, DateTimeParse</b></code></dt>
						<dd>Implements the <a href="#ParserParsePattern"><i>Parser/Parse pattern</i></a>
							for <code>System.DateTime</code> values.
							More flexible (for both the programmer and the user)
							than <code>System.DateTime.Parse</code> and 
							<code>System.DateTime.TryParse</code>.</dd>

					<dt><code><b>DateParser, DateParse</b></code></dt>
						<dd>Implements the <a href="#ParserParsePattern"><i>Parser/Parse pattern</i></a>
							for dates only (not times).  Recognizes any reasonable, unambiguous date format.</dd>

					<dt><code><b>TimeParser, TimeParse</b></code></dt>
						<dd>Implements the <a href="#ParserParsePattern"><i>Parser/Parse pattern</i></a>
							for times only (not dates).</dd>

					<dt><code><b>TimeSpanParser, TimeSpanParse</b></code></dt>
						<dd>Implements the <a href="#ParserParsePattern"><i>Parser/Parse pattern</i></a>
							for <code>System.TimeSpan</code> values.  Recognizes input like
							"3&nbsp;days", "123.5&nbsp;hrs", and "100ms", 
							as well as variations on "1d&nbsp;23:45:06.789".</dd>

				</dl>
			
			</div>

		</div>


		<hr />
		<a name="Footnotes" />
		<b>Footnotes</b>
		<p class="footnote"><b>1.</b> Thanks to Jerry Curry for inspiring me to document my justifications.</p>
		<p class="footnote"><b>2.</b> Thanks to Mike Mintz for introducing me to Assertions.</p>
		<p class="footnote"><b>3.</b> If you didn't understand this sentence, then just ignore it.</p>
		<p class="footnote"><b>4.</b> In other words, a mathematical proof of correctness of your code.</p>
		<p class="footnote"><b>5.</b> This means <i>measuring</i> the performance with that particular 
								assertion in place, and then measuring it again with that assertion removed.</p>
		<p class="footnote"><b>6.</b> Yes, <i>parser</i> and <i>parse</i> aren't the greatest word choices.
								A case could be made in favor of <i>lexer</i> and <i>lexeme</i>, but the .Net
								framework already uses the word <i>Parse</i>, and consistency won out over
								correctness this time.  <i>ParseResult</i> would also be more accurate,
								but I felt that names like <i>DateTimeParseResult</i> were too unwieldy.</p>

		<div class="license">
			<p>Copyright 2011-2014 Edward L. Stauff. &nbsp;	Contact: <a href="mailto:EdStauff@gmail.com">EdStauff@gmail.com</a></p>
			<p>
				This file is part of the "Stauffware.Essentials" library.             
				"Stauffware.Essentials" is free software: you can redistribute it     
				and/or modify it under the terms of the GNU Lesser Public License as published     
				by the Free Software Foundation, either version 3 of the License, or (at your      
				option) any later version.                                                         
			</p><p>
				"Stauffware.Essentials" is distributed in the hope that it will       
				be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of          
				MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser           
				Public License for more details.                                                   
			</p><p>
				You should have received a copy of the GNU Lesser Public License along with        
				"Stauffware.Essentials".  If not, see 
				<a href="http://www.gnu.org/licenses/">http://www.gnu.org/licenses/</a>. 
			</p>
		</div>
	</body>
</html>

